package com.cw.jeeyt.service.utils;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cw.jeeyt.common.Constants;
import com.cw.jeeyt.dao.intf.system.SystemAttachDao;
import com.cw.jeeyt.dao.model.system.SystemAttachDo;

/**
 * 清理多余的附件记录的任务
 *
 * @author chenw
 */
public class ClearDirtyAttachTimer {

    private static final Logger logger = LoggerFactory.getLogger(ClearDirtyAttachTimer.class);

    private SystemAttachDao systemAttachDao;

    public void execute() {
        clearDirtyAttach();
    }

    /**
     * 清理没有用的附件信息
     */
    public void clearDirtyAttach() {
        try {
            List<SystemAttachDo> dirtyList = systemAttachDao.getDirtyAttachListByObjectId();
            for (SystemAttachDo attach : dirtyList) {
                String fileType = attach.getFileType();
                if (Constants.ATTACH_DB.equals(fileType)) {
                    // 存储在数据库中的文件
                    systemAttachDao.delete(attach);
                } else if (Constants.ATTACH_DIRECTORY.equals(fileType)) {
                    // 存储在磁盘目录中的文件
                    String fileDir = attach.getFileDir();
                    String fileName = attach.getFileName();
                    File file = new File(fileDir + fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                } else if (Constants.ATTACH_DIRECTORY_DB.equals(fileType)) {
                    systemAttachDao.delete(attach);
                    String fileDir = attach.getFileDir();
                    String fileName = attach.getFileName();
                    File file = new File(fileDir + fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("定时器清理冗余的附件信息时出错", e);
            e.printStackTrace();
        }

    }

    public void setSystemAttachDao(SystemAttachDao systemAttachDao) {
        this.systemAttachDao = systemAttachDao;
    }

}
